package com.wuqi.dev;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        Document rootDoc = reader.read(new File("fruit-list.xml"));

        DocumentHelper.createDocument();

        Element rootElement = rootDoc.getRootElement();
        System.out.println(rootElement.getName());

        Iterator<Element> iterator = rootElement.elementIterator();
        while (iterator.hasNext()){
            Element next = iterator.next();
            String name = next.attributeValue("name");
            System.out.println(name);
            Iterator<Element> musicIterator = next.elementIterator();
            while (musicIterator.hasNext()){
                Element music = musicIterator.next();
                String n = music.element("name").getText();
                String d = music.element("duration").getText();
                System.out.println(n);
                System.out.println(d);
            }


        }

        Document doc = DocumentHelper.createDocument();
        Element albumList = doc.addElement("albumList");
        Element album = albumList.addElement("album");
        album.addAttribute("name", "八度空间");
        Element music = album.addElement("music");
        Element name = music.addElement("name");
        name.setText("半兽人");

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(new FileWriter("output.xml"),format);
        writer.write(doc);
        writer.flush();
        writer.close();

        Gson gson = new Gson();
        Type t1 = TypeToken.getArray(Test.class).getType();
        Type t2 = TypeToken.get(List.class).getType();
        Type t3 = new TypeToken<List<Test>>(){}.getType();
        List<Test> o = gson.fromJson(new FileReader("test.json"), t3);
        System.out.println(o.get(0).getClass().getName());

    }
}
